--[[
 	下载更新
 		2016_04_27 C.P
 	功能：下载替换文件资源
]]--
local ClientUpdate = class("ClientUpdate")

-- url:下载list地址 
-- wirtepath:保存路径
-- curfile:当前list路径
function ClientUpdate:ctor(newfileurl,savepath,kindID,zipmd5,listener)
	self._newfileurl = newfileurl
	self._savepath = savepath
	self._kindID = kindID
	self._retryCount = 0
	self._listener = listener
	-- local verinfo = string.split(zipmd5,"_")
	self._zipmd5 = zipmd5 --verinfo[2] or ""
	-- self._zipver = verinfo[1] or 0

end


function ClientUpdate:setSetUpDateClient(listener)
	self._listener = listener
end

function ClientUpdate:upDateClient(listener)

	--创建文件夹
	if not createDirectory(self._savepath) then
		print( "创建文件夹失败>>>>>>>>>>>！")
	end
	self:cleanPackageLoaded(self._kindID)
	self._newfileurl = self._newfileurl
	local dstpath = device.writablePath.."download/"
	local filename = self._kindID..".zip"
	-- cc.FileUtils:getInstance():removeDirectory(dstpath .. self._kindID.."/")
	print("upDateClient>>>",self._newfileurl ,dstpath,filename)
	self:downZipFileAsync(self._newfileurl ,filename,dstpath,self._zipmd5,function(main,sub)
		print("UpdateFile	main,sub>>>>",	main,sub,self._listener )
			--下载回调
			if not tolua.isnull(self._listener)  and main == appdf.DOWN_PRO_INFO then --进度信息
				if self.per and self.per > sub then
					sub = self.per
				else
					self.per =  sub
				end
				self.progressPercent = sub
				self._listener:updateProgress(sub,self._kindID , sub ,self._kindID)
			elseif main == "md5_error" then 
				cc.FileUtils:getInstance():removeFile(dstpath .. filename)
				yl.updateList[self._kindID] = nil
				if not tolua.isnull(self._listener)  then
					self._listener:updateResult(false,"更新文件校验失败,点击确定重试",self._kindID) --失败信息
				end

			elseif main == appdf.DOWN_COMPELETED then --下载完毕
				cc.FileUtils:getInstance():removeFile(dstpath .. filename)
				
				-- 		--通知完成
				yl.updateList[self._kindID] = 0
				if not tolua.isnull(self._listener) then
					yl.updateList[self._kindID] = nil
					self._listener:updateResult(true,"下载成功",self._kindID)
				end
				
			elseif main == appdf.DOWN_ERROR_NET then 
				cc.FileUtils:getInstance():removeFile(dstpath .. filename)
				yl.updateList[self._kindID] = nil
				if not tolua.isnull(self._listener)  then
					self._listener:updateResult(false,"下载失败"..(sub or "0"),self._kindID) --失败信息
				end
			elseif self._listener.updateResult  then
				self._listener:updateResult(false,main or "下载失败",self._kindID) --失败信息
			end
		end)

end

--下载
function ClientUpdate:UpdateFile()
	

end

function ClientUpdate.checkFile(fileName, cryptoCode)
    print("checkFile:", fileName)
    -- print("cryptoCode:", cryptoCode)

    if not io.exists(fileName) then
        return false
    end

    local data=readFile(fileName)
    if data==nil then
        return false
    end

    if cryptoCode==nil then
        return true
    end

    local ms = md5(hex(data))
    print("file cryptoCode:", ms,cryptoCode)
    if ms==cryptoCode then
        return true
    end

    return false
end

 function hex(s)
 s=string.gsub(s,"(.)",function (x) return string.format("%02X",string.byte(x)) end)
 return s
end

 function readFile(path)
    local file = io.open(path, "rb")
    if file then
        local content = file:read("*all")
        io.close(file)
        return content
    end
    return nil
end

function ClientUpdate:cleanPackageLoaded( kindid )
	for k ,v in pairs(package.loaded) do
		if k ~= nil then 
			if type(k) == "string" then
				if string.find(k,""..kindid) ~= nil then
					print("package kill:"..k) 
					package.loaded[k] = nil
				end
			end
		end
	end	
	display.removeUnusedSpriteFrames()
end

function ClientUpdate:downZipFileAsync( url,filename,storagePath,zipmd5,callback,parent )
	cc.FileUtils:getInstance():removeFile(storagePath..filename)
	cc.FileUtils:getInstance():removeFile(storagePath .. filename..".tmp")
	local assetsManagerEx = cc.AssetsManagerEx:create("project.manifest", storagePath)
	print("assetsManagerEx>>>>",url,filename,storagePath,callback)
	assetsManagerEx:retain()
	local eventListenerAssetsManagerEx 
	local dispatcher = cc.Director:getInstance():getEventDispatcher()

    -- 设置下载消息listener
	local function handleAssetsManagerEx(event)

		local eventcode  = event:getEventCode()
		print("upDateClient>>>>>>>",eventcode)
        if (cc.EventAssetsManagerEx.EventCode.UPDATE_PROGRESSION ==eventcode) then
			print("更新进度=" .. event:getPercent())
			callback(appdf.DOWN_PRO_INFO,event:getPercent())
			return
        end

        if (cc.EventAssetsManagerEx.EventCode.UPDATE_FINISHED == eventcode) then
            print("更新完毕，重新启动>>>")
			dispatcher:removeEventListener(eventListenerAssetsManagerEx)
			if not tolua.isnull(assetsManagerEx) then
				assetsManagerEx:release()
            else
                return
            end
			assetsManagerEx=nil
			local path = cc.FileUtils:getInstance():fullPathForFilename(filename) 
			print("path>>11111>>>>",path)
			if not path or path == "" or not cc.FileUtils:getInstance():isFileExist(path) then
				path = device.writablePath.."download/"..filename
				print("path>>22222>>>>",path)
				-- path = cc.FileUtils:getInstance():fullPathForFilename("0_"..filename)
				if not path or path == "" or not cc.FileUtils:getInstance():isFileExist(path) then
					local btmp =  cc.FileUtils:getInstance():isFileExist(filename..".tmp") 
					cc.FileUtils:getInstance():removeFile(storagePath..filename)
					cc.FileUtils:getInstance():removeFile(storagePath .. filename..".tmp")
					callback("找不到更新文件"..filename)
				end
			end
            local filemd5 =  MD5File(path) or ""
            
            print("handleAssetsManagerEx>>>>>>>>>>",filename,zipmd5 , filemd5,path)
            if string.upper(trim(zipmd5)) ~= string.upper(filemd5) then
				callback("md5_error")
				cc.FileUtils:getInstance():removeFile(path)
				cc.FileUtils:getInstance():removeFile(path..".tmp")
                return 
            end
			unZipAsync(path,storagePath,function(result)
				print("onUnZipBase result client >>>>>",result)
				-- parent._txtTips:setString("解压文件，请稍候....")
				if checkint(result) == 1 then
					callback(appdf.DOWN_COMPELETED)
					cc.FileUtils:getInstance():removeFile(path)
					cc.FileUtils:getInstance():removeFile(path..".tmp")
				else
					cc.FileUtils:getInstance():removeFile(path)
					cc.FileUtils:getInstance():removeFile(path..".tmp")
					callback("解压失败")
				end
			end)
            return
        -- elseif (cc.EventAssetsManagerEx.EventCode.ERROR_UPDATING == eventcode) then
        --     return
        end

		print("发生错误:更新失败")
		callback(appdf.DOWN_ERROR_NET,eventcode)
		-- cc.FileUtils:getInstance():removeFile(storagePath..filename)
		cc.FileUtils:getInstance():removeFile(storagePath .. filename..".tmp")
        if not tolua.isnull(assetsManagerEx) then
			assetsManagerEx:release()
			dispatcher:removeEventListener(eventListenerAssetsManagerEx)
			assetsManagerEx=nil
        end
    end
 
    eventListenerAssetsManagerEx = cc.EventListenerAssetsManagerEx:create(assetsManagerEx, handleAssetsManagerEx)
	dispatcher:addEventListenerWithFixedPriority(eventListenerAssetsManagerEx, 1)
	
    -- 检查版本并升级
	assetsManagerEx:toload(url,storagePath..filename)
	-- assetsManagerEx:update()
	return assetsManagerEx,dispatcher
end


return ClientUpdate